package com.huitone.smspfm.task;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import com.huitone.smspfm.core.config.AppStaticConfigs;
import com.huitone.smspfm.logger.ExtLogger;

/**   
* @Title GetPriListLengthTask.java 
* @Package com.huitone.smspfm.task 
* @Description TODO(用一句话描述该文件做什么) 
* @author ybliang   
* @date 2017年9月10日 下午4:23:36 
* @version V1.0   
*/
public class GetPriListLengthTask extends Thread {
	
	private static final ExtLogger logger = ExtLogger.create(GetPriListLengthTask.class);
	
	public static Map<String, Long> priListLength = new ConcurrentHashMap<String, Long>();
	
	private long excuteInterval = 300000;
	
	private boolean keepGoing = true;

	@Override
	public void run() {
		
		@SuppressWarnings("rawtypes")
		RedisScript<List> script = new DefaultRedisScript<List>(AppStaticConfigs.luaGetPriListLength, List.class);
		
		List<String> keys = new ArrayList<>();
		keys.add(AppStaticConfigs.iSMPriListNamesSet);
		
		while (!this.isInterrupted() && isKeepGoing()) {
			
			List<String> priListNames = new ArrayList<String>();
			
			try {
				
				Cursor<Object> oldPriList = AppStaticConfigs.setOpts3.scan(AppStaticConfigs.iSMPriListNamesSet, ScanOptions.NONE);
				while (oldPriList.hasNext()) {
					priListNames.add((String) oldPriList.next());
				}
				
				oldPriList.close();
				
				List<Long> list = AppStaticConfigs.scriptOpts3.getListLong(script, keys, priListNames.toArray());
				
				if (list != null && !list.isEmpty()) {
					
					for (int i = 0 ; i < priListNames.size() ; i ++) {
						priListLength.put(priListNames.get(i), list.get(i));
					}
					
					Iterator<Entry<String, Long>> iterator = priListLength.entrySet().iterator();
					while(iterator.hasNext()) {
						Entry<String, Long> entry = iterator.next();
						if (!priListNames.contains(entry.getKey())) {
							iterator.remove();
						}
					}
				}
				
			} catch (Exception e) {
				logger.error("获取优先级队列长度的任务中报错!", e);
			}
			
			try {
				Thread.sleep(excuteInterval);
			} catch (InterruptedException e) {}
		}
	}

	public boolean isKeepGoing() {
		return keepGoing;
	}

	public void setKeepGoing(boolean keepGoing) {
		this.keepGoing = keepGoing;
	}

	@Override
	public void destroy() {
		this.setKeepGoing(false);
		this.interrupt();
	}

}
